<template>
	<view class="cart-container">
		<!-- <view v-if="isEmpty" class="empty-cart">
			<image src="/static/images/empty-cart.png" mode="aspectFit"></image>
			<text>购物车空空如也,去选点东西吧...</text>
		</view> -->
		<!-- 购物车商品列表 -->
		<scroll-view scroll-y class="goods-list" :style="{height: scrollHeight + 'px'}">
			<view class="goods-item" v-for="(item, index) in cartList" :key="index">
				<view class="item-left">
					<checkbox-group @change="toggleSelect(index)">
						<checkbox :checked="item.selected" :value="item.id" />
					</checkbox-group>
				</view>
				<view class="item-right">
					<image class="goods-img" :src="item.image" mode="aspectFill"></image>
					<view class="goods-info">
						<text class="goods-title">{{item.name}}</text>
						<text class="goods-spec">{{item.spec}}</text>
						<view class="goods-bottom">
							<text class="goods-price">¥{{item.price}}</text>
							<view class="stepper">
								<text class="minus" @click="changeNum(index, -1)">-</text>
								<input type="number" v-model="item.quantity" @change="checkNum(index)" />
								<text class="plus" @click="changeNum(index, 1)">+</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部结算栏 -->
		<view class="cart-footer">
			<view class="footer-left">
				<checkbox-group @change="toggleAll">
					<checkbox :checked="isAllSelected" />全选
				</checkbox-group>
			</view>
			<view class="footer-right">
				<view class="total-price">
					合计: <text class="price">¥{{totalPrice}}</text>
				</view>
				<view class="btn-settle" @click="goToSettle">
					去结算({{selectedCount}})
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {mapState,mapActions} from 'vuex'
	export default {
		data() {
			return {
				// isEmpty:false,
				scrollHeight: 0,
				cartList: [],
			}
		},
		computed: {
			...mapState('userAbout',['userInfo']),
			// 是否全选
			isAllSelected() {
				return this.cartList.every(item => item.selected) && this.cartList.length > 0
			},
			// 选中商品总价
			totalPrice() {
				return this.cartList.reduce((total, item) => {
					return item.selected ? total + item.price * item.quantity : total
				}, 0).toFixed(2)
			},
			// 选中商品数量
			selectedCount() {
				return this.cartList.reduce((count, item) => {
					return item.selected ? count + item.quantity : count
				}, 0)
			}
		},
		onShow() {
			this.getCartList()
		},
		onLoad() {
			// 计算scroll-view高度
			this.calcScrollHeight()
		},
		methods: {
			...mapActions('cartAbout',['setCart']),
			async getCartList() {
				this.cartList = []
				try{
					const res = await this.$myRequest({
						url: '/api/cart/list',
						data: {
							checked: 'checked',
							userId:this.userInfo.id
						}
					})
					console.log('carts', res)
					//用户登录成功后，将进入购物车页面，此时将购物车中物品数量记录下来,便于在商品列表页角标显示用户购物数量
					this.setCart(res.data.data.length)
					//这里不能用状态码进行判断，因为即便是购物车是空的，但是后台返回的状态码也是200
					if(res.data.data.length!=0){
						let list = res.data.data
						list.forEach((item) => {
							this.cartList.push({
								productId:item.productId.toString(),
								detailId: item.detailId.toString(),
								name: item.product.name,
								image: item.detail.image,
								spec: item.detail.name,
								price: item.detail.salePrice,
								quantity: item.quantity,
								selected: true
							})
						})
					}
					else{
						// this.isEmpty=true
						uni.showToast({
							title:'您尚未购物,去选点喜欢的东西吧',
							duration:2000,
							success() {
								setTimeout(()=>{
									uni.switchTab({
										url:'/pages/index/index'
									})
								},2000)
							}
						})
					}
				}catch(e){
					console.log(e)
					uni.showToast({
						title:'请先登录',
						duration:1500,
						success() {
							setTimeout(()=>{
								uni.switchTab({
									url:'/pages/member/member'
								})
							},1500)
						}
					})
				}
			},
			calcScrollHeight() {
				const systemInfo = uni.getSystemInfoSync()
				this.scrollHeight = systemInfo.windowHeight - 50 // 减去底部结算栏高度
			},
			// 切换单个商品选中状态
			toggleSelect(index) {
				this.cartList[index].selected = !this.cartList[index].selected
				this.saveCartData()
			},
			// 全选/反选
			toggleAll() {
				const selectAll = !this.isAllSelected
				this.cartList.forEach(item => {
					item.selected = selectAll
				})
				this.saveCartData()
			},
			// 修改商品数量
			changeNum(index, num) {
				const newNum = this.cartList[index].quantity + num
				if (newNum < 1) {
					uni.showToast({
						title: '商品数量不能小于1',
						icon: 'none'
					})
					return
				}
				if (newNum > 99) {
					uni.showToast({
						title: '商品数量不能超过99',
						icon: 'none'
					})
					return
				}
				this.cartList[index].quantity = newNum
				this.saveCartData()
			},
			// 校验输入的数量
			checkNum(index) {
				let num = parseInt(this.cartList[index].quantity)
				if (isNaN(num) || num < 1) {
					num = 1
				} else if (num > 99) {
					num = 99
				}
				this.cartList[index].quantity = num
				this.saveCartData()
			},
			// 删除商品
			deleteGoods(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该商品吗？',
					success: res => {
						if (res.confirm) {
							this.cartList.splice(index, 1)
							this.saveCartData()
						}
					}
				})
			},
			// 保存购物车数据
			saveCartData() {
				// 实际项目中应保存到缓存或调用接口
				uni.setStorageSync("cartList",this.cartList)
			},
			// 去结算
			goToSettle() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none'
					})
					return
				}
				const selectedGoods = this.cartList.filter(item => item.selected)
				//uni.navigateTo 是通过 URL 参数传递数据的，而 URL 仅支持字符串类型的数据，
				//所以需要先把数组转换为字符串，在目标页面再将其转换回数组。
				uni.navigateTo({
					url: '/pages/order/confirm?data=' + JSON.stringify(selectedGoods)+'&totalPrice=' + this.totalPrice
				})
			}
		}
	}
</script>
<style scoped>
	.cart-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f4f4f4;
	}

	.goods-list {
		flex: 1;
		overflow: hidden;
	}

	.goods-item {
		display: flex;
		margin: 10px;
		padding: 10px;
		background-color: #fff;
		border-radius: 8px;
	}

	.item-left {
		display: flex;
		align-items: center;
		margin-right: 10px;
	}

	.item-right {
		flex: 1;
		display: flex;
	}

	.goods-img {
		width: 100px;
		height: 100px;
		border-radius: 4px;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin-left: 10px;
	}

	.goods-title {
		font-size: 14px;
		line-height: 18px;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.goods-spec {
		margin-top: 5px;
		font-size: 12px;
		color: #999;
	}

	.goods-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: auto;
	}

	.goods-price {
		color: #e93b3d;
		font-size: 16px;
		font-weight: bold;
	}

	.stepper {
		display: flex;
		align-items: center;
	}

	.stepper input {
		width: 40px;
		height: 26px;
		text-align: center;
		border: 1px solid #eee;
		margin: 0 5px;
	}

	.stepper text {
		display: inline-block;
		width: 26px;
		height: 26px;
		line-height: 26px;
		text-align: center;
		border: 1px solid #eee;
		background-color: #f8f8f8;
	}

	.cart-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 50px;
		padding: 0 10px;
		background-color: #fff;
		border-top: 1px solid #eee;
	}

	.footer-left {
		display: flex;
		align-items: center;
	}

	.footer-right {
		display: flex;
		align-items: center;
	}

	.total-price {
		margin-right: 15px;
		font-size: 14px;
	}

	.price {
		color: #e93b3d;
		font-weight: bold;
	}

	.btn-settle {
		padding: 8px 20px;
		background-color: #e93b3d;
		color: #fff;
		border-radius: 20px;
		font-size: 14px;
	}
</style>
